﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Selectors;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;

namespace SharpShare.IdentityModel {
    public class AggregateSecurityTokenAuthenticator : SecurityTokenAuthenticator {
        public AggregateSecurityTokenAuthenticator(IEnumerable<SecurityTokenAuthenticator> authenticators) {
            this.Authenticators = authenticators.ToList().AsReadOnly();
        }

        public ReadOnlyCollection<SecurityTokenAuthenticator> Authenticators { get; private set; }

        protected override bool CanValidateTokenCore(System.IdentityModel.Tokens.SecurityToken token) {
            return this.Authenticators.Any(a => a.CanValidateToken(token));
        }

        protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) {
            var policies = this.Authenticators
                .Where(a => a.CanValidateToken(token))
                .SelectMany(a => a.ValidateToken(token))
                .ToList();

            return policies.AsReadOnly();
        }
    }
}
